from geopy.distance import geodesic

from common.request import requestutil
from config import config

key = config.gd_app_key



def get_address(address, city):
    url = "https://restapi.amap.com/v3/place/text" \
          "?key=%s&citylimit=true&output=json&keywords=%s&city=%s" % (key, address, city)
    response = requestutil.get(url)
    data = response.json()
    pois = data.get("pois", [])
    # addr = {
    #     'name': '上海人民广场','type': '风景名胜;公园广场;城市广场','typecode': '110105',
    #     'address': '人民大道120号','location': '121.475173,31.228814','pname': '上海市',
    #     'cityname': '上海市','adname': '黄浦区'}
    addr = {}
    if len(pois) > 0:
        pois0 = pois[0]
        addr['name'] = pois0.get("name", "")
        addr['type'] = pois0.get("type", "")
        addr['typecode'] = pois0.get("typecode", "")
        addr['address'] = pois0.get("address", "")

        # 高德的经纬度是(经,纬)(121.475173,31.228814)
        # 但是计算距离,以及网上反向查询地址都是(纬,经),(31.232781, 121.475137)
        # 转换一下, 成(纬,经)的格式
        location = pois0.get("location", "").split(',')
        location2 = [float(location[1]), float(location[0])]
        addr['location'] = tuple(location2)
        addr['pname'] = pois0.get("pname", "")
        addr['cityname'] = pois0.get("cityname", "")
        addr['adname'] = pois0.get("adname", "")
    return addr


def get_location(address, city):
    addr = get_address(address, city)
    return addr.get("location")


def geodistance(geo1, geo2):
    # 计算两个坐标直线距离
    # (维,经)
    # geo1 = (30.28708, 120.12802999999997)
    # geo2 = (28.7427, 115.86572000000001)
    distance = geodesic(geo1, geo2)  # 计算两个坐标直线距离
    # print(distance.km)
    return distance.km

if __name__=="__main__":
    geo_人民广场 = (31.232781, 121.475137)
    geo1 = get_location("杨巷东区", "上海")
    print(geo1)
    km = geodistance(geo1, geo_人民广场)
    print(km)
    geo1 = get_location("七宝老街", "上海")
    print(geo1)
    km = geodistance(geo1, geo_人民广场)
    print(km)
